package com.cl.short_video_java.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cl.short_video_java.common.Const;
import com.cl.short_video_java.pojo.VideoUser;
import com.cl.short_video_java.pojo.VideoUserFollowed;
import com.cl.short_video_java.service.VideoUserFollowedService;
import com.cl.short_video_java.mapper.VideoUserFollowedMapper;
import com.cl.short_video_java.service.VideoUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author object
 * @description 针对表【video_user_followed】的数据库操作Service实现
 * @createDate 2024-11-24 10:26:38
 */
@Service
public class VideoUserFollowedServiceImpl extends ServiceImpl<VideoUserFollowedMapper, VideoUserFollowed>
		implements VideoUserFollowedService {

	private VideoUserService videoUserService;

	public VideoUserFollowedServiceImpl(VideoUserService videoUserService) {
		this.videoUserService = videoUserService;
	}

	/**
	 * 获取用户关注列表-被关注列表
	 *
	 * @param type
	 * @param current
	 * @param request
	 * @return
	 */
	@Override
	public Page<VideoUserFollowed> concern(Integer type, Integer current, HttpServletRequest request) {
		VideoUser user = videoUserService.getCurrentUser(request, Const.GRADE_USER);

		Page<VideoUserFollowed> page = this.page(new Page<>(current, 20), new QueryWrapper<VideoUserFollowed>()
				.eq(type == 1, "uid", user.getId())
				.eq(type == 2, "followed_uid", user.getId())
				.eq("status", 1)
				.orderByDesc("create_time")
		);

		for (VideoUserFollowed videoUserFollowed : page.getRecords()) {
			VideoUser videoUser = videoUserService.getOne(new QueryWrapper<VideoUser>()
					.select("id", "avatar", "nickname")
					.eq(type == 1, "id", videoUserFollowed.getFollowedUid())
					.eq(type == 2, "id", videoUserFollowed.getUid())
			);
			videoUser.setIsFollowed(type == 1 ? 1 : 0);
			videoUserFollowed.setUser(videoUser);
		}


		return page;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void followed(Integer type, Integer uid, HttpServletRequest request) {
		VideoUser user = videoUserService.getCurrentUser(request, Const.GRADE_USER);
		long count = videoUserService.count(new QueryWrapper<VideoUser>()
				.eq("id", uid)
				.eq("status", 1)
				.eq("is_delete", 0));
		Assert.isTrue(count == 1, "当前账号不存在或被封禁");
		VideoUserFollowed one = this.getOne(new QueryWrapper<VideoUserFollowed>()
				.eq("uid", user.getId())
				.eq("followed_uid", uid)

		);
		one.setUid(user.getId());
		one.setFollowedUid(uid);
		one.setStatus(type);
		one.setCreateTime(LocalDateTime.now());
		this.saveOrUpdate(one);
	}
}




